﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Maticsoft.DBUtility;
using Aspose.Words;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using System.Collections;
using System.Text;
using System.IO;

using System.Windows.Forms;
using System.Drawing;

namespace SkWeb.FAXZ
{
    public partial class FACX : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
          
         
                {
                    btnFirst.Text = "最首页";
                    btnPrev.Text = "前一页";
                    btnNext.Text = "下一页";
                    btnLast.Text = "最后页";
                    ViewState["Filter"] = "";
                    GridViewTable_Load();
                }
            }
        }


        protected void GridViewTable_Load()
        {
            string strJh = Request["jh"].ToString();
            string strFa = Request["fa"].ToString();
            string strSql = "select * from tb_sjfa where name='" + strFa + "'";
            DataTable dt = OracleHelper.Query(strSql).Tables[0];
            string strPkTableName = dt.Rows[0]["PKTABLENAME"].ToString();
            string strPkFiedName = dt.Rows[0]["PKFIELD"].ToString();
            string strFaId = dt.Rows[0]["ID"].ToString();
            strSql = "select * from tb_bookmark where faid =" + strFaId;
            DataTable dtBM = OracleHelper.Query(strSql).Tables[0];
            DataColumn dc = new DataColumn("VALUE", Type.GetType("System.String"));
            dtBM.Columns.Add(dc);
            FillTable(dtBM, strJh);
            gv.DataSource = dtBM;
            gv.DataBind();

            lblCurrentIndex.Text = "第<font color='red'>" + (gv.PageIndex + 1).ToString() + " </font>页";
            lblPageCount.Text = "总共 <font color='red'>" + gv.PageCount.ToString() + " </font>页";
        }

        void FillTable(DataTable dt, string pkValue)
        {
            foreach (DataRow dr in dt.Rows)
            {
                string strFormula = dr["FORMULA"].ToString();
                if (string.IsNullOrEmpty(strFormula.Trim()))
                {
                    string name = dr["NAME"].ToString();
                    string text = dr["TEXT"].ToString();
                    string tablename = dr["TABLENAME"].ToString();
                    string fieldname = dr["FIELDNAME"].ToString();
                    string pkfield = dr["PKFIELD"].ToString();
                    string strSql = "select " + fieldname + " from " + tablename + " where " + pkfield + "='" + pkValue + "' ";
                    string strValue = OracleHelper.Query(strSql).Tables[0].Rows[0][0].ToString();
                    dr["VALUE"] = strValue;
                }
                else
                {
                    DataTable dtFormula = OracleHelper.Query("select * from tb_formula where name='" + strFormula + "' ").Tables[0];
                    string pktable = dtFormula.Rows[0]["PKTABLENAME"].ToString();
                    string pkfield = dtFormula.Rows[0]["PKFIELDNAME"].ToString();
                    string Content = dtFormula.Rows[0]["VALUE"].ToString();

                    DataTable dtVars = OracleHelper.Query("select * from tb_formula_var where name ='" + strFormula + "' ").Tables[0];
                    foreach (DataRow drVar in dtVars.Rows)
                    {
                        string varName = drVar["BKNAME"].ToString();
                        string strTable = drVar["TABLENAME"].ToString();
                        string strField = drVar["FIELDNAME"].ToString();
                        string strpkField = drVar["PKFIELDNAME"].ToString();
                        string strVarValue = OracleHelper.Query(" select " + strField + " from " + strTable + " where " + strpkField + "='" + pkValue + "' ").Tables[0].Rows[0][0].ToString();
                        Content = Content.Replace(varName, strVarValue);
                    }
                    CodeDriver driver = new CodeDriver();
                    bool isError;
                    string strResult = driver.ComplileAndRun(Content, out isError);//调用执行代码的类
                    dr["VALUE"] = strResult;
                }
            }
            dt.AcceptChanges();

        }

        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //throw new NotImplementedException();
        }


        protected void btnGenDoc_Click(object sender, EventArgs e)
        {
            string strFa = Request["fa"].ToString();
            string strJh = Request["jh"].ToString();
            string strSql = "select filepath from tb_sjfa where name='" + strFa + "' ";
            string docPath = OracleHelper.Query(strSql).Tables[0].Rows[0][0].ToString();

           Aspose.Words.Document tempDocument;
           Aspose.Words.DocumentBuilder builder;
            tempDocument = new Aspose.Words.Document(docPath);
            builder = new DocumentBuilder(tempDocument);
            //builder.CellFormat.ClearFormatting();
            //builder.Font.Size = 10;
            //builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            //builder.RowFormat.Alignment = Aspose.Words.Tables.RowAlignment.Left;
            //builder.RowFormat.AllowAutoFit = true;

            // 井号
            foreach (GridViewRow dr in gv.Rows)
            {
                if (dr.RowType == DataControlRowType.DataRow)
                {
                    tempDocument.Range.Bookmarks[dr.Cells[0].Text].Text = (dr.FindControl("txtValue") as System.Web.UI.WebControls.TextBox).Text;
                }
            }
            string strPath = Server.MapPath("~/tempDoc/") + strJh + "_" + strFa + ".doc";
            tempDocument.Save(strPath, SaveFormat.Doc);
            byte[] fileBytes = File.ReadAllBytes(strPath);
            File.Delete(strPath);
            Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strPath, System.Text.Encoding.UTF8));
            Response.AddHeader("Content-Length", fileBytes.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.Charset = "GB2312";
            Response.BinaryWrite(fileBytes);
            Response.Flush();
            Response.End();

        }
        protected void btnBack_Click(object sender, EventArgs e)
        {
            getModelGZ();//for test
           // Response.Write("<script language=javascript>history.go(-2);</script>");
        }

        protected void btnBrowse_Click(object sender, EventArgs e)
        {
            string strFa = Request["fa"].ToString();
            string strJh = Request["jh"].ToString();
            string strSql = "select filepath from tb_sjfa where name='" + strFa + "' ";
            string docPath = OracleHelper.Query(strSql).Tables[0].Rows[0][0].ToString();
           Aspose.Words.Document tempDocument;
           
            DocumentBuilder builder;
            tempDocument = new Aspose.Words.Document(docPath);
            builder = new DocumentBuilder(tempDocument);
          
            // 井号
            foreach (GridViewRow dr in gv.Rows)
            {
                if (dr.RowType == DataControlRowType.DataRow)
                {
                    tempDocument.Range.Bookmarks[dr.Cells[0].Text].Text = (dr.FindControl("txtValue") as System.Web.UI.WebControls.TextBox).Text;
                }
            }
            string strPath = Server.MapPath("~/tempDoc/") + strJh + "_" + strFa + ".doc";
            tempDocument.Save(strPath, SaveFormat.Doc);



            Response.Redirect("WordBrowse.aspx?name=" + Server.UrlEncode(strJh + "_" + strFa + ".doc"));
        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            string arg = ((LinkButton)sender).CommandArgument.ToString();
            switch (arg)
            {
                case "next":
                    gv.PageIndex = gv.PageIndex + 1;
                    break;
                case "prev":
                    if (gv.PageIndex > 0)
                    {
                        gv.PageIndex = gv.PageIndex - 1;
                    }
                    break;
                case "last":
                    gv.PageIndex = gv.PageCount - 1;
                    break;
                case "0":
                    gv.PageIndex = 0;
                    break;
            }
            GridViewTable_Load();
        }

        protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gv.PageIndex = e.NewPageIndex;
            //ViewState["page"]=
            GridViewTable_Load();
        }

        /// <summary>
        /// 得到管住页面所需的数据对象
        /// </summary>
        /// <returns></returns>
        protected modelGZ getModelGZ()
        {

            string strFa = Request["fa"].ToString();
            string strJh = Request["jh"].ToString();
            string strSql = "select filepath from tb_sjfa where name='" + strFa + "' ";
            string docPath = OracleHelper.Query(strSql).Tables[0].Rows[0][0].ToString();
            OfficeDocIO.OpenWord(docPath);
            OfficeDocIO.GetWordTableContent(2,1,1,2,Server.MapPath("~/")+"tempImg/ge.jpg");
            OfficeDocIO.CloseWord();
            //Document document;
           
            //document = new Document(docPath);
            //Node node= document.GetChild(NodeType.Table, 2, true);
            //node.Range.FormFields
            //for (int j = 1; j <= (document.Tables.Item(1).Columns.Count); j++)
            //{
            //    for (int i = 1; i <= (document.Tables.Item(1).Rows.Count); i++)
            //    {
            //        MessageBox.Show("行:" + i.ToString() + "列:" + j.ToString() + "内容：" + mydoc.Tables.Item(1).Cell(i, j).Range.Text);
            //    }
            //} 



            modelGZ model = new modelGZ();
            return model;
        }





    }

    public class modelGZ
    {
        double dingwei_;
        int len_;
        double oilTop_;
        double oilBotton_;

        public double dingwei
        {
            get { return dingwei_;}
            set { dingwei_ = value; }
        }
        public int len
        {
            get { return len_; }
            set { len_ = value; }
        }
        public double oilTop
        {
            set { oilTop_ = value; }
            get { return oilTop_; }
        }
        public double oilBotton
        {
            set { oilBotton_=value; }
            get { return oilBotton_; }
        }
    }



    public class OfficeDocIO
    {
        private static Microsoft.Office.Interop.Word._Application appWord = null;
        private static Microsoft.Office.Interop.Word._Document docWord = null;

        /// <summary>
        /// 打开一个Word文档，相对的方法是CloseWord()
        /// </summary>
        /// <param name="file">文件名</param>
        /// <returns></returns>
        public static bool OpenWord(string file)
        {
            appWord = new Microsoft.Office.Interop.Word.Application();
            object path = file;
            object missing = System.Reflection.Missing.Value;
            object readOnly = true;
            try
            {
                docWord = appWord.Documents.Open(ref path, ref missing, ref readOnly, ref missing,
                                      ref missing, ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing, ref missing);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                appWord = null;
                return false;
            }
        }

        /// <summary>
        /// 提取word文档中表格的内容
        /// </summary>
        /// <param name="tableid">表格索引</param>
        /// <param name="rowIndex">行号</param>
        /// <param name="colIndex">列号</param>
        /// <param name="type">内容类型 1为文本 2为图片</param>
        /// <returns>提取出来的内容</returns>
        public static object GetWordTableContent(int tableid, int rowIndex, int colIndex, int type,string path)
        {
            if (docWord != null && docWord.Tables.Count > tableid - 1)
            {
                object content = null;
                try
                {
                    switch (type)
                    {
                        case 1:
                            if (docWord.Tables[tableid].Rows.Count > (rowIndex - 1)
                                && docWord.Tables[tableid].Columns.Count > (colIndex - 1))
                            {
                                content = docWord.Tables[tableid].Cell(rowIndex,

colIndex).Range.Text.ToString();
                            }
                            break;
                        case 2:
                            if (docWord.Tables[tableid].Rows.Count > (rowIndex - 1) &&
                                docWord.Tables[tableid].Columns.Count > (colIndex - 1))
                            {
                                if (docWord.Tables[tableid].Cell(rowIndex,

colIndex).Range.InlineShapes.Count > 0)
                                {
                                    foreach (Microsoft.Office.Interop.Word.InlineShape ish
                                        in docWord.Tables[tableid].Cell(rowIndex,

colIndex).Range.InlineShapes) //目前处理的word文档中只有一张图片
                                    {
                                        if (ish.Type ==

Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture ||
                                            ish.Type ==

Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapeLinkedPicture)
                                        {
                                            ish.Select();
                                            appWord.Selection.Copy();
                                            System.Drawing.Image image = Clipboard.GetImage();
                                            Bitmap bitmap = new Bitmap(image);
                                            bitmap.Save(path );
    //                                        System.Drawing.Image image =

//System.Windows.Forms.Clipboard.GetImage();
//                                            content = image;
                                            if (image == null)
                                            {
                                                content = ish;
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }

                    return content;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return null;
        }

        /// <summary>
        /// 关闭打开的word文档
        /// </summary>
        public static void CloseWord()
        {
            object missing = System.Reflection.Missing.Value;
            try
            {
                if (docWord != null)
                {
                    docWord.Close(ref missing, ref missing, ref missing);
                    docWord = null;
                }
                if (appWord != null)
                {
                    appWord.Quit(ref missing, ref missing, ref missing);
                    appWord = null;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }








    public class CodeDriver
    {
        private string prefix = "using System;" +
        "public static class Driver" +
        "{" +
        "public static void Run()" +
        "{  Console.Write( ";
        private string postfix = ");}" + "}";
        public string ComplileAndRun(string input, out bool hasError)
        {
            hasError = false;
            string returnData = null;
            CompilerResults results = null;
            using (CSharpCodeProvider provider = new CSharpCodeProvider())//c#代码生成器和编译器的实例
            {
                CompilerParameters options = new CompilerParameters();
                options.GenerateInMemory = true;//是否从内存输出
                StringBuilder sb = new StringBuilder();
                sb.Append(prefix);
                sb.Append(input);
                sb.Append(postfix);


                results = provider.CompileAssemblyFromSource(options, sb.ToString());//向编译器输入代码字符

            }
            if (results.Errors.HasErrors)//代码运行是否正常
            {
                hasError = true;
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendFormat("{0} {1}", error.Line, error.ErrorText);
                }
                returnData = sb.ToString();
            }
            else
            {
                TextWriter tw = Console.Out;
                StringWriter sw = new StringWriter();
                Console.SetOut(sw);//接受输出的字符串
                Type driverType = results.CompiledAssembly.GetType("Driver");//反射获取Driver类
                //指定执行函数的参数列表
                driverType.InvokeMember("Run", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, null);

                Console.SetOut(tw);
                returnData = sw.ToString();
            }
            return returnData;
        }
    }
}